<?php

namespace app\common\service;

/**
 * @description 会员统一逻辑，解决之前soa2从soa迁移出来的会员逻辑分散的情况 
 * 
 */
use app\common\model\jooj_member\ViewMemberIndex as ViewMemberIndexModel;
use app\common\model\jooj_member\MemberIndex as MemberIndexModel;
use app\common\model\jooj_member\MemberIndexInfo as MemberIndexInfoModel;
use app\common\model\jooj_member\MemberVip as MemberVipModel;
use app\common\model\oms\MemberSign as MemberSignModel;
use app\common\model\jsm\Members as MembersModel;

use app\common\service\arvato\ArvatoMemberService;
use app\common\common\Helper;
use app\common\model\oms\Companies as CompaniesModel;

class MemberGetwayService {

    /**
     * 更新会员信息
     * @param type $params
     * @param type $type
     * @throws \Exception
     */
    public function updateMemberInfo($params, $type) {

        $ViewMemberIndexModel = new ViewMemberIndexModel($params['company_id']);
        $where = [];
        switch ($type) {
            case 'OPENID':
                $where = ['account_code' => "{$params['account_code']}"];
                $this->needMerge($params['company_id'], $type, "{$params['account_code']}");
                break;
            case 'MEMBERCODE':
                $where = ['member_code' => "{$params['member_code']}"];
                break;
            case 'WXUNIONID':
                $where = ['wx_union_id' => "{$params['wx_union_id']}"];
                $this->needMerge($params['company_id'], $type, "{$params['wx_union_id']}");
                break;
            default :
                throw new \Exception('更新条件不正确!');
        }

        //主体思想，如果本身有手机号，判断有没有对应数据，如果有（提示不可以），如果没有（可以直接绑定，然后继续）
        $this->autoMergeByMobile($params, $params['company_id'], $type);
        //与以上的顺序不可交换--autoMergeByMobile
        $view = $ViewMemberIndexModel->getViewMemberIndexByCondition($where);

        //如果对应的(伪)视图不存在
        if (empty($view)) {
            //注册会员
            $this->registerMemberInfo($params, $params['company_id']);
            $newView = $ViewMemberIndexModel->getViewMemberIndexByCondition($where);
            return ['code' => 200, 'msg' => 'add', 'data' => $newView];
        }

        $ViewMemberIndexModel->startTrans();

        $jj_uni_id = isset($view['jj_uni_id']) ? $view['jj_uni_id'] : '';
        if (empty($jj_uni_id)) {
            throw new \Exception('the member jj_uni_id is empty');
        }

        $memberIndexModel = new MemberIndexModel($params['company_id']);
        $memberCodeArr = $memberIndexModel->getMemberCodeArrByUniId($jj_uni_id);
        $this->updateViewField($params['company_id'], $params, $memberCodeArr);

        $memberIndexInfoModel = new MemberIndexInfoModel($params['company_id']);
        $memberIndexInfoModel->clearBindData($memberCodeArr);


        //如果是更新的话，那么有没有可能成为VIP会员
        $canVip = $this->canVip($jj_uni_id, $params['company_id'], $params);
        if ($canVip === true) {
            //平台版逻辑创建卡号
            try{
                $arvatoMemberService = new ArvatoMemberService();
                $data = $arvatoMemberService->updateMemberInfo_sync($jj_uni_id, $params['company_code']);
                if (isset($data['card_level'])) {
                    $Info = ['card_lev' => $data['card_level']];
                    $this->updateViewField($params['company_id'], $Info, $memberCodeArr, $params['openId']);
                }
            }catch(\Exception $ex){
                throw new \Exception($ex->getMessage());
            }

            $memberVipModel = new MemberVipModel($params['company_id']);
            $vipId = $memberVipModel->addMemberVip($params);
            if (empty($vipId)) {
                throw new \Exception('创建VIP表数据失败');
            }

            //回写vip_id到memberIndex表(一定要更新到手机号的那条上去)
            $updatememberIndex = $memberIndexModel->updateMemberIndex(['mobile' => $params['mobile'], 'member_code' => ['in', $memberCodeArr]], ['vip_id' => $vipId]);
            if ($updatememberIndex === false) {
                throw new \Exception('更新memberIndex中VIPID失败');
            }
        }

        if ($params['company_code'] == 'baodao') {
            $arvatoMemberService = new ArvatoMemberService();
            $arvatoMemberService->updateMemberInfo($jj_uni_id, $params['company_code']);
        }

        $newView = $ViewMemberIndexModel->getViewMemberIndexByCondition($where);
        $ViewMemberIndexModel->commit();
        //判断最新的数据是否符合成为VIP的可能
        return ['code' => 200, 'msg' => 'update', 'data' => $newView];
    }

    /**
     * 添加粉丝信息，调用处（1、微信关注；2、arvato请求解绑接口）
     * @param type $mpId
     * @param type $openid
     * @param type $companyId
     * @return boolean
     */
    public function addFansInfo($mpId, $openid, $companyId) {

        $membersModel = new MembersModel($mpId);
        $membersModel->startTrans();

        $members = $membersModel->getMembersByCondition(['openid' => $openid]);
        if (empty($members)) {
            return ['msg' => "jsm members ({$mpId}) don't have {$openid} record"];
        }


        $memberIndexModel = new MemberIndexModel($companyId);
        $memberIndex = $memberIndexModel->getMemberIndexByOpenId($openid);

        if ($memberIndex) {
            return ['msg' => "memberindex table have {$openid} have record"];
        }

        //插入memberIndex
        $params = [];
        $params['mobileStatus'] = 2;
        $params['name'] = $members['nickname'];
        $params['come_from'] = 32;
        $params['gender'] = $members['gender'];
        $params['header_img'] = $members['headimgurl'];
        $params['birthday'] = $members['birth_day'];
        $params['mp_id'] = $this->_mpId;
        $params['account_code'] = $openid;

        $memberCode = $memberIndexModel->addMemberIndex($params);
        if ($memberCode === false) {
            return ['msg' => "memberindex table insert fail"];
        }

        //插入memberIndexinfo
        $paramsInfo = [];
        $memberIndexInfoModel = new MemberIndexInfoModel($companyId);
        $res = $memberIndexInfoModel->addMemberInfo($paramsInfo, $memberCode);
        if ($res === false) {
            return ['msg' => "memberindexinfo table insert fail"];
        }

        $membersModel->commit();

        $CompanyModel = new CompaniesModel();
        $Company = $CompanyModel->getCompanyInfoByCondition('*', ['company_id' => $companyId], true);

        $ViewMemberIndexModel = new ViewMemberIndexModel($companyId);
        $ViewMemberIndex = $ViewMemberIndexModel->getViewMemberIndexByCondition(['account_code' => $openid]);

        //推送给arvato
        //$ArvatoMemberService = new ArvatoMemberService();
        //$ArvatoMemberService->newMember($ViewMemberIndex['jj_uni_id'], $Company['company_code']);
        $MemberGetwayService = new MemberGetwayService();
        $Card = $MemberGetwayService->createCardNo($ViewMemberIndex['jj_uni_id'], $Company['company_code']);
        if (!isset($Card['cardno'])) {
            return ['msg' => "cardno create is fail"];
        }
        $result = $memberIndexModel->updateMemberIndex(['account_code' => $openid], ['cardno' => $Card['cardno'], 'card_lev' => $Card['card_lev']]);
        if ($result === false) {
            return ['msg' => "update cardno is fail"];
        }

        return true;
    }

    /**
     * 此方法是针对于手机号进行自动合并逻辑
     * 主体思想，如果本身有手机号，判断有没有对应数据，如果有（提示不可以），如果没有（可以直接绑定，然后继续）
     * 
     * @param type $params
     * @param type $companyId
     * @param type $type
     */
    private function autoMergeByMobile($params, $companyId, $type) {

        if (!isset($params['mobile']) || !isset($params['mobile_status']) || $params['mobile_status'] != 1) {
            return true;
        }

        $ViewMemberIndexModel = new ViewMemberIndexModel($companyId);
        $MemberIndexModel = new MemberIndexModel($companyId);
        $MemberIndexInfoModel = new MemberIndexInfoModel($companyId);

        switch ($type) {
            case 'OPENID':
                $mobileView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $params['mobile'], 'mobile_status' => 1]);
                if (!empty($mobileView) && !empty($mobileView['account_code'])) {
                    throw new \Exception("autoMergeByMobile mobile has already bind openid");
                }

                //获取openid下的view是否存在
                $openIdView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['account_code' => "{$params['account_code']}"]);

                //暴力方式（反正都是合并，所以没必要管有没有记录，有记录不管直接合并，没记录就插入）
                if (empty($mobileView)) {
                    //插入
                    $result = $this->registerMemberInfo($params, $companyId);
                    //重新找到记录
                    $jJUniId = isset($result['jj_uni_id']) ? $result['jj_uni_id'] : '';
                    if (empty($jJUniId)) {
                        throw new \Exception('autoMergeByMobile:手机号注册失败！');
                    }

                    $mobileView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['jj_uni_id' => $jJUniId]);
                }

                if (empty($openIdView)) {
                    //插入
                    unset($params['mobile']);
                    unset($params['mobile_status']);
                    $result = $this->registerMemberInfo($params, $companyId);
                    $jJUniId = isset($result['jj_uni_id']) ? $result['jj_uni_id'] : '';
                    if (empty($jJUniId)) {
                        throw new \Exception('autoMergeByMobile:openid注册失败！');
                    }

                    $openIdView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['jj_uni_id' => $jJUniId]);
                }

                //直接绑定，因为以上已经确保（2条或者1条完整数据）
                $memberCode = $openIdView['member_code'];
                $jJUniId = $mobileView['jj_uni_id'];

                $memberCodeArr = $MemberIndexModel->bindMemberIndex('mutil', '', '', $memberCode, $jJUniId);
                if (empty($memberCodeArr)) {
                    throw new \Exception('autoMergeByMobile：绑定数据失败！');
                }
                //绑定完毕需要清理数据
                $MemberIndexInfoModel->clearBindData($memberCodeArr);

                break;
            case 'MEMBERCODE':
                $mobileView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $params['mobile'], 'mobile_status' => 1]);
                if (!empty($mobileView) && ($mobileView['account_code'])) {
                    throw new \Exception("autoMergeByMobile memberCode mobile is not empty");
                }
                if(!empty($mobileView) && empty($mobileView['account_code'])){
                    //需要做绑定
                    $memberCodeArr = $MemberIndexModel->bindMemberIndex('mutil', '', '', $params['member_code'], $mobileView['jj_uni_id']);
                    if (empty($memberCodeArr)) {
                        throw new \Exception('autoMergeByMEMBERCODE：绑定数据失败！');
                    }
                    //绑定完毕需要清理数据
                    $MemberIndexInfoModel->clearBindData($memberCodeArr);
                }
                break;
            case 'WXUNIONID':
                $mobileView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $params['mobile'], 'mobile_status' => 1]);

                if (!empty($mobileView) && !empty($mobileView['wx_union_id'])) {
                    throw new \Exception("autoMergeByMobile mobile has already bind wx_union_id");
                }
                //获取openid下的view是否存在
                $UnionIdView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['wx_union_id' => "{$params['wx_union_id']}"]);
                //暴力方式（反正都是合并，所以没必要管有没有记录，有记录不管直接合并，没记录就插入）
                if (empty($mobileView)) {
                    //插入
                    $result = $this->registerMemberInfo($params, $companyId);
                    //重新找到记录
                    $jJUniId = isset($result['jj_uni_id']) ? $result['jj_uni_id'] : '';
                    if (empty($jJUniId)) {
                        throw new \Exception('autoMergeByMobile:手机号注册失败！');
                    }

                    $mobileView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['jj_uni_id' => $jJUniId]);
                }

                if (empty($UnionIdView)) {
                    //插入
                    unset($params['mobile']);
                    unset($params['mobile_status']);
                    $result = $this->registerMemberInfo($params, $companyId);
                    $jJUniId = isset($result['jj_uni_id']) ? $result['jj_uni_id'] : '';
                    if (empty($jJUniId)) {
                        throw new \Exception('autoMergeByMobile:openid注册失败！');
                    }

                    $UnionIdView = $ViewMemberIndexModel->getViewMemberIndexByCondition(['jj_uni_id' => $jJUniId]);
                }

                //直接绑定，因为以上已经确保（2条或者1条完整数据）
                $memberCode = $UnionIdView['member_code'];
                $jJUniId = $mobileView['jj_uni_id'];

                $memberCodeArr = $MemberIndexModel->bindMemberIndex('mutil', '', '', $memberCode, $jJUniId);
                if (empty($memberCodeArr)) {
                    throw new \Exception('autoMergeByMobile：绑定数据失败！');
                }
                //绑定完毕需要清理数据
                $MemberIndexInfoModel->clearBindData($memberCodeArr);
                break;
            default :
                throw new \Exception("autoMergeByMobile type is error");
        }
    }

    /**
     * 判断有没有两条数据一样的（open_id及wx_union_id）
     * @param type $companyId
     * @param type $type
     * @param type $value
     * @return boolean
     */
    private function needMerge($companyId, $type, $value) {
        $where = [];
        $ViewMemberIndexModel = new ViewMemberIndexModel($companyId);
        switch ($type) {
            case 'OPENID':
                $where = ['account_code' => "{$value}"];
                $viewMemberIndexList = $ViewMemberIndexModel->getViewMemberListByCondition($where);
                if (count($viewMemberIndexList) > 1) {
                    //合并数据
                    $this->MergeData($viewMemberIndexList, $companyId);
                }
                break;
            case 'WXUNIONID':
                $where = ['wx_union_id' => "{$value}"];
                $viewMemberIndexList = $ViewMemberIndexModel->getViewMemberListByCondition($where);
                if (count($viewMemberIndexList) > 1) {
                    //合并数据
                    $this->MergeData($viewMemberIndexList, $companyId);
                }
                break;
            default :
                //直接返回不需要合并
                return true;
        }
    }

    /**
     * 合并数据
     * @param type $viewMemberIndexList
     * @param type $companyId
     * @return boolean
     */
    private function MergeData($viewMemberIndexList, $companyId) {

        $MemberIndexModel = new MemberIndexModel($companyId);
        $jj_uni_id = current($viewMemberIndexList)['jj_uni_id'];


        $memberCodeArr = [];
        foreach ($viewMemberIndexList as $view_item) {
            $memberCodeArr = $MemberIndexModel->bindMemberIndex('mutil', '', '', $view_item['member_code'], $jj_uni_id);
        }

        $MemberIndexInfoModel = new MemberIndexInfoModel($companyId);
        $MemberIndexInfoModel->clearBindData($memberCodeArr);

        return true;
    }

    /**
     * 判断是否有条件成为VIP可以成为Vip
     * @param type $jj_uni_id
     * @param type $company_id
     * @param type $params
     * @return boolean
     * @throws \Exception
     */
    private function canVip($jj_uni_id, $company_id, $params) {

        /*
         * note:本来本方法是需要暴露异常的的，但是由于之前存在很多合并逻辑
         * 所以对于合并后的数据，不做异常抛出，只是不向下操作了
         */

        $ViewMemberIndexModel = new ViewMemberIndexModel($company_id);
        $view = $ViewMemberIndexModel->getViewMemberIndexByCondition(['jj_uni_id' => $jj_uni_id]);
        //如果手机号已经认证
        if (isset($params['mobile_status']) && $params['mobile_status'] == 1 && isset($params['mobile']) && $params['mobile']) {
            //如果当前用户的手机号已经注册过了，那么就不可以绑定了
            if (!empty($view['vip_id'])) {
                //throw new \Exception('该用户已经成为VIP了！');
                return false;
            }
            //查询这个手机号是否已经注册成为会员
            $brotherView = $ViewMemberIndexModel->getViewInfoByCondition(['mobile' => "{$params['mobile']}", 'jj_uni_id' => ['neq', $jj_uni_id]]);
            //防止手机号和状态不在一条memberIndex记录上，仅在一条memberView上
            foreach ($brotherView as $item) {
                if ($item['mobile_status'] == 1) {
                    //throw new \Exception('该手机号已经被绑定了！');
                    return false;
                }
            }

            return true;
        }

        return false;
    }

    /**
     * 注册会员信息
     * @param type $params
     */
    public function registerMemberInfo($params, $companyId) {

        $memberIndexInfoModel = new MemberIndexInfoModel($companyId);
        $memberIndexModel = new MemberIndexModel($companyId);
        $memberVipModel = new MemberVipModel($companyId);
        $viewMemberModel = new ViewMemberIndexModel($companyId);

        $memberRecord = $this->checkIndexMember($params, $companyId);

        $memberIndexInfoModel->startTrans();

        switch ($params['mobile_status']) {
            //注册VIP用户
            case 1:
                if ($memberRecord && isset($params['mobile'])) {
                    throw new \Exception('此手机号已经被注册过了,请换个手机号试试');
                }
                //添加VIP会员
                $returnData = $this->addMemberInfo($params, $companyId, 'VIP');
                break;
            //注册潜客/粉丝    
            default:
                //这个是给pad端来作为潜客的入口
                if ($memberRecord && !isset($params['mobile'])) {
                    $params['member_code'] = $memberRecord['member_code'];
                    //更新写入账号服务信息表
                    $memberIndexInfoModel->updateIndexInfo($params);
                    $data = $viewMemberModel->getIndexAndvipData(['member_code' => $params['member_code']]);

                    return ['code' => 200, 'msg' => '已经存在相同的账号信息', 'data' => $data];
                } else if ($memberRecord && isset($params['mobile'])) {
                    throw new \Exception('此手机号已经被注册过了,请换个手机号试试');
                }
                //添加粉丝/潜客
                $returnData = $this->addMemberInfo($params, $companyId, 'FANS');
                break;
        }

        //推送数据给arvato
        $jjUniId = isset($returnData['data']['jj_uni_id']) ? $returnData['data']['jj_uni_id'] : '';
        if (empty($jjUniId)) {
            throw new \Exception('获取jjUniId失败');
        }

        $companyCode = $params['company_code'];

        if (!isset($returnData['data']['cardno'])) {
            //有cardno不需要再创建
            $createCarNo = $this->createCardNo($jjUniId, $companyCode);
        } else {
            $createCarNo['cardno'] = $params['cardno'];
            $createCarNo['card_lev'] = $params['card_lev'];
        }

        $memberCode = isset($returnData['data']['member_code']) ? $returnData['data']['member_code'] : '';
        if (empty($memberCode)) {
            throw new \Exception('获取memberCode失败！');
        }

        if (!empty($createCarNo['cardno'])) {

            $updataMemberInfo = $memberIndexModel->updateMemberIndex(['member_code' => $returnData['data']['member_code']], $createCarNo);
            if ($updataMemberInfo === false) {
                throw new \Exception('卡号更新到memberIndex失败！');
            }

            $updataMemberVipInfo = $memberVipModel->updateMemberVip(['member_code' => $returnData['data']['member_code']], $createCarNo);
            if ($updataMemberVipInfo === false) {
                throw new \Exception('卡号更新到memberVip失败！');
            }
        }

        $returnData['data']['cardno'] = $createCarNo['cardno'];
        $returnData['data']['cardLev'] = $createCarNo['card_lev'];

        $memberIndexInfoModel->commit();


        $signData = [
            'member_code'   => $memberCode,
            'vipId'         => '',
            'service_store' => isset($params['first_store']) ? $params['first_store'] : '',
            'come_from'     => 4,
            'service_p'     => isset($params['first_p']) ? $params['first_p'] : '',
            'cardno'        => isset($createCarNo['cardno']) ? $createCarNo['cardno'] : '',
            'mobile'        => isset($params['mobile']) ? $params['mobile'] : '',
        ];

        //通过companyId获取companyCode(此处可以优化)
        $CompaniesModel = new CompaniesModel();
        $Companies = $CompaniesModel->getCompanyInfoByCondition('*', ['company_id' => $companyId], true);
        //调用会员签到方法
        $memberSignModel = new MemberSignModel($companyId);
        $memberSignModel->memberCheckin($signData, $Companies['company_code']);


        return ['code' => 200, 'msg' => 'success', 'data' => $returnData['data'], 'jj_uni_id' => $jjUniId];
    }

    /**
     * 生成会员卡号规则
     * @author
     * @date 2016-03-25
     * @param int $JjUniId jj_uni_id
     * @param int $companyCode 公司编号
     * @param int $head 卡号头
     */
    public function createCardNo($JjUniId = '', $companyCode = '', $head = 99) {
        if ($companyCode == 'baodao') {
            $ArvatoMemberService = new ArvatoMemberService();
            $data = $ArvatoMemberService->newMember($JjUniId, $companyCode);
            if (!isset($data['card_no'])) {
                //throw new \Exception('会员卡号生成失败！['.__LINE__.']');
                return ['cardno' => '', 'card_lev' => 0];
            }
            return ['cardno' => $data['card_no'], 'card_lev' => $data['card_level']];
        }

        $CompaniesModel = new CompaniesModel();
        $Companies = $CompaniesModel->getCompanyInfoByCondition('*', ['company_code' => $companyCode]);
        $ViewMemberIndexModel = new ViewMemberIndexModel($Companies['company_id']);
        $View = $ViewMemberIndexModel->getViewMemberIndexByCondition(['jj_uni_id' => $JjUniId]);

        //平台版逻辑
        if (isset($View) && $View['mobile_status'] == 1 && empty($View['card_no'])) {
            $cardno = (string) $head . substr(Helper::createNumber(), 2);
            return ['cardno' => $cardno, 'card_lev' => 0];
        }

        //自我保护机制（防止以外进入的）
        return ['cardno' => null, 'card_lev' => 0];
    }

    /**
     * 实行(伪)视图单字段更新
     * 
     * 注：不用jj_uni_id的原因，是为了尽量少的参数完成工作
     * 因为更新memberIndexInfo的条件只能是memberCode
     * 
     * @param type $companyId
     * @param type $params
     * @param type $memberCodeArr
     * @param type $openId
     * @return boolean
     */
    public function updateViewField($companyId, $params, $memberCodeArr, $openId = '') {

        $memberIndexModel = new MemberIndexModel($companyId);
        $memberIndexInfoModel = new MemberIndexInfoModel($companyId);

        //如果openId不为空，也需要geng
        //开启事务
        $memberIndexModel->startTrans();
        foreach ($params as $key => $item) {
            //如果key在这个目录下，就更新memberIndex对应数据
            $IndexParams = ['vip_id', 'mobile_status', 'name', 'gender', 'birthday', 'header_img',
                'mp_id', 'cardno', 'card_lev', 'mobile', 'account_code', 'wx_union_id'];
            //修改memberIndex的时候会涉及到这几个字段的同步问题
            $vipParams = ['name', 'gender', 'birthday', 'cardno'];
            //如果key在这个目录下，就更新memberIndexInfo对应的数据
            $IndexInfoParams = ['service_p', 'service_store', 'service_qrscene'];

            //如果发现改字段是memberIndex需要更新的字段，就去更新
            if (array_search($key, $IndexParams) !== false) {
                $memberIndexModel->updateValue($key, $item, $memberCodeArr);
            }

            //如果发现这个是memberVip需要更新的，并且有vip信息的，才做相关的更新
            if (array_search($key, $vipParams) !== false) {

                $viewMemberIndexModel = new ViewMemberIndexModel($companyId);
                //首先查到vip_id,然后根据vip_id去修改vip表的数据
                $memberCode = current($memberCodeArr);
                $vwhere = empty($openId)?['member_code' => $memberCode]:['account_code'=>$openId];
                $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition($vwhere);
                if ($viewMemberIndex && !empty($viewMemberIndex['vip_id'])) {
                    //更新vip表
                    $memberVipModel = new MemberVipModel($companyId);
                    $vipId = $viewMemberIndex['vip_id'];
                    $memberVipModel->updateValue($key, $item, $vipId);
                }
            }

            //如果发现是memberIndexInfo需要更新的字段，做相关更新
            if (array_search($key, $IndexInfoParams) !== false) {
                $memberIndexInfoModel->updateValue($key, $item, $memberCodeArr);
            }
        }

        $memberIndexModel->commit();
        return true;
    }

    /**
     * 注册会员/粉丝/潜客
     * @param type $params
     * @param type $companyId
     * @param type $type
     * @return type
     * @throws \Exception
     */
    private function addMemberInfo($params, $companyId, $type) {

        $memberVipModel = new MemberVipModel($companyId);
        $memberIndexInfoModel = new MemberIndexInfoModel($companyId);
        $memberIndexModel = new MemberIndexModel($companyId);

        $memberIndexModel->startTrans();

        $memberCode = $memberIndexModel->addMemberIndex($params);
        if ($memberCode === false) {
            throw new \Exception('创建memberIndex表数据失败');
        }
        $newMemberIndex = $memberIndexModel->getMemberInfoByCondition(['member_code' => $memberCode]);
        $params['member_code'] = $newMemberIndex['member_code'];
        $params['jj_uni_id'] = $newMemberIndex['jj_uni_id'];
        //写入账号服务信息表
        $addMemberIndexInfo = $memberIndexInfoModel->addMemberInfo($params, $newMemberIndex['member_code']);

        if (false === $addMemberIndexInfo) {
            throw new \Exception('创建memberIndexInfo表数据失败');
        }

        $message = '粉丝';

        //只有当是VIP的时候，才会去做相关操作
        if ($type != 'FANS') {
            //写入到正式会员表
            $vipId = $memberVipModel->addMemberVip($params);
            if (empty($vipId)) {
                throw new \Exception('创建VIP表数据失败');
            }

            //回写vip_id到memberIndex表
            $updatememberIndex = $memberIndexModel->updateMemberIndex(['member_code' => $memberCode], ['vip_id' => $vipId]);
            if (empty($updatememberIndex)) {
                throw new \Exception('更新memberIndex中VIPID失败');
            }

            $message = '正式会员';
        }


//        $signData = [
//            'member_code' => $memberCode,
//            'vipId' => $vipId,
//            'service_store' => $params['first_store'],
//            'come_from' => 4,
//            'service_p' => $params['first_p'],
//        ];
//        //通过companyId获取companyCode
//        $CompaniesModel = new CompaniesModel();
//        $Companies = $CompaniesModel->getCompanyInfoByCondition('*', ['company_id'=>$companyId]);
//        //调用会员签到方法
//        $memberSignModel = new MemberSignModel($companyId);
//        $memberSignModel->memberCheckin($signData,$Companies['company_code']);

        $memberIndexModel->commit();
        return ['code' => 200, 'msg' => '恭喜您,注册' . $message . '成功', 'data' => $params];
    }

    /**
     * 注册验证是否存在  在手机注册验证的时候就已经验证过了 这里再次验证下 但不返回数据了
     * @param type $params
     * @return type []
     */
    private function checkIndexMember($params, $companyId) {
        $MemberIndexModel = new MemberIndexModel($companyId);
        if (empty($params['mobile']) && !isset($params['mobile'])) {
            $condition = [
                'name'     => $params['name'],
                'birthday' => $params['birthday'],
                'gender'   => $params['gender'],
            ];
            return $MemberIndexModel->getMemberInfoByCondition($condition, '*', 'member_code desc');
        }

        if (!empty($params['mobile'])) {
            return $MemberIndexModel->getMemberInfoByCondition(['mobile' => $params['mobile'], 'mobile_status' => 1], '*', 'member_code desc');
        }

        return false;
    }

}
